import React from 'react';
import { Upload ,Button,notification,message} from 'antd';
import { UploadOutlined ,DeleteOutlined,PauseCircleOutlined , DownloadOutlined} from '@ant-design/icons';
import http from 'axios'
import OSS from 'ali-oss'
import '../index.scss'


class App extends React.Component {
  state = {
    fileList: this.props.video?[{url:this.props.video,status: 'done'}]:[],
    disabled:this.props.disabled
  };

  video = React.createRef();
  canvas = React.createRef();

  componentWillReceiveProps(nextProps){
    let self = this;
    self.setState({
      disabled:nextProps.disabled
    })
    self.setState({ fileList:nextProps.value?[{url:nextProps.value,status: 'done'}]:[] });
    }

    handleChange = ({ fileList }) => {
      this.setState({ fileList:fileList.filter(i=>i.status==='done') });
    }

  handleMove = (file) =>{
    this.setState({
      fileList:[...this.state.fileList].filter(i=>i.status==='done')
    })
  }

  customRequest = (file) => {
    var suffix = file.file.name.substr(file.file.name.indexOf('.')) // 获取文件后缀名
    var filename = new Date().getTime() + suffix // 为文件命名

    const token =  window.location.href.indexOf('/prd') === -1 ?localStorage.getItem('token-llx-test'):localStorage.getItem('token-llx')

    http({
      method: 'post',
      url:  window.location.href.indexOf('/prd')===-1?'http://139.224.81.105:19999/qia-cloud-filesystem/OSS/companies/getStsToken':'http://139.224.81.105:9999/qia-cloud-filesystem/OSS/companies/getStsToken',
      headers: { 'Authorization':'Bearer ' + token }
    }).then(res => {
      const fileData = res
      var bucket = 'middle-file'
      var region = 'oss-cn-shanghai'
      var type = ''
      const client = new OSS({
        region,
        accessKeyId: fileData.accessKeyId,
        accessKeySecret: fileData.accessKeySecret,
        stsToken: fileData.stsToken,
        bucket
      })
      
      type = 'video'
      client.multipartUpload(type + '/' + filename, file.file).then((result) => {
        var url = result.res.requestUrls[0]
        var length = url.lastIndexOf('?')
        var getUrl = length > 0 ? url.substr(0, length) : url // 文件最终路径


        this.setState({
          fileList:[...this.state.fileList,{url:getUrl,status: 'done'}].filter(i=>i.status==='done')
        })
          
        this.props.setVideo(getUrl)

      }).catch(function(err) {
        notification.error({
          description:'上传失败',
          duration:1
        })
      })
  }).catch(err=>{
    notification.error({
      description:'上传失败',
      duration:1
    })
  })
  }
  
    // 删除
    removeVideo = () => {
      this.setState({
        fileList:[]
      },()=>{
        this.props.setVideo('')
      })
    }
    // 下载
    downloadVideo = () => {
      window.open(this.state.fileList[0].url)
    }
    // 截图
    cutPicture = () => {
      var v = this.video.current
      const canvas =this.canvas.current
      var ctx = canvas.getContext('2d')
      ctx.drawImage(v, 0, 0, 400, 226)
    }
    // 上传
    cutUploadPicture = (event) => {
      const items = (event.clipboardData || window.clipboardData).items
      let file = null

      if (!items || items.length === 0) {
        message.error('当前浏览器不支持本地')
        return
      }
      // 搜索剪切板items
      console.log(items);
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          break
        }
      }
      if (!file) {
        message.error('粘贴内容非图片')
        return
      }
      this.addFile(file)
    }

    addFile= async (file) => {
      if (file.type.indexOf('image') >= 0) {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 'image')
        const baseUrl = window.location.href.indexOf('/prd')
        const res = await http({
          url: baseUrl === -1 ? 'http://139.224.81.105:19999/qia-cloud-filesystem/fileUpload' : 'http://139.224.81.105:9999/qia-cloud-filesystem/fileUpload',
          method: 'post',
          data: formData
        })
       this.props.replacePicture(res.result)
      }
    }
    

  
    render() {
      const { fileList , disabled} = this.state;

    return (
      <div className='video-upload'>
        <div>
        <Upload
          name='file'
          accept="video/*"
          action="#"
          fileList={fileList}
          onChange={this.handleChange}
          onRemove={this.handleMove}
          customRequest={this.customRequest}
          maxCount={1}
          progress={this.progress}
          showUploadList={false}
        >
          <Button disabled={disabled} type='primary' icon={<UploadOutlined />}>上传视频</Button>
        </Upload>

        {
          fileList.length===1?<div>

          
           <DownloadOutlined className='icon' onClick={this.downloadVideo}/>

         

           {
             disabled?'':<> 
               <DeleteOutlined  className='icon' onClick={this.removeVideo}/>
             
             <Button style={{marginTop:'-20px'}} size={'small'} type={"primary"} onClick={this.cutPicture}>截图</Button>
           
             <span style={{marginTop:'-20px'}} className='text-link' onPaste={this.cutUploadPicture}>上传截图</span></>
           }
          </div>:''
        }
        </div>
        {
          fileList.length===1?<div>
            <video ref={this.video} controls width={400} height={226} src={fileList[0].url}></video>


            <canvas ref={this.canvas}  width="400" height="226" />
          </div>:''
        }

      </div>
    );
  }
}

export default App;